package com.util;

import android.app.Activity;
import android.content.ContentProviderOperation;
import android.content.Context;
import android.os.Environment;
import android.os.FileUtils;

import com.entity.Authority;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class HttpUtils{
    public final static String Api="http://120.24.50.23:8081/api/";
    public static final MediaType JSON= MediaType.parse("application/json; charset=utf-8");
    private static OkHttpClient client = new OkHttpClient();
    public  static String Get(String url){
        try {
            Request request = new Request.Builder()
                    .url(Api+url)
                    .header("Authorization",Authority.getAuthorization())
                    .build();
            Response response = client.newCall(request).execute();
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    public static String Post(String url, String json){
        try {
            OkHttpClient client = new OkHttpClient();
                RequestBody body = RequestBody.create(JSON, json);
                Request request = new Request.Builder()
                        .url(Api+url)
                        .post(body)
                        .header("Authorization", Authority.getAuthorization())
                        .build();
                Response response = client.newCall(request).execute();
            return response.body().string();
        }catch (IOException e){
            e.printStackTrace();
            return null;
        }
    }
    public static String Put(String url,String json){

        try {
            OkHttpClient client = new OkHttpClient();
            RequestBody body = RequestBody.create(JSON, json);
            Request request = new Request.Builder()
                    .url(Api+url)
                    .put(body)
                    .header("Authorization",Authority.getAuthorization())
                    .build();
            Response response = client.newCall(request).execute();
            return response.body().string();
        }catch (IOException e){
            e.printStackTrace();
            return null;
        }
    }
    public static String Delete(String url,String json){
        try {
            OkHttpClient client = new OkHttpClient();
            RequestBody body = RequestBody.create(JSON, json);
            Request request = new Request.Builder()
                    .url(Api+url)
                    .delete(body)
                    .header("Authorization",Authority.getAuthorization())
                    .build();
            Response response = client.newCall(request).execute();
            return response.body().string();
        }catch (IOException e){
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 下载文件
     * */
    public static void downloadFile(Context context, String url,IDownload download) {
        final long startTime = System.currentTimeMillis();
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Connection", "close")
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                String savePath = context.getFilesDir().getPath();
                File path=new File(savePath);
                if(!path.exists()){
                    path.mkdir();
                }
                try {
                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    File file = new File(path.getPath(), url.substring(url.lastIndexOf("/") + 1));
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        download.DownloadProgress(progress);
                    }
                    fos.flush();
                    download.DownloadSucceed(true,(System.currentTimeMillis() - startTime), file.getPath());
                } catch (Exception e) {
                    download.DownloadException(e);
                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException ignored) {
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException ignored) {
                    }
                }
            }
        });
    }
    public interface IDownload {
        /**
         * 下载进度
         * */
        void DownloadProgress(double progress);
        /**
         * 下载是否成功
         * */
        void DownloadSucceed(boolean isSucceed,long elapsedTime,String path);
        /**
         *下载异常
         * */
        void DownloadException(Exception e);
    }


}
